package sc.tool.sqlgen.branchinfo;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.springframework.util.CollectionUtils;

import sc.prototype.common.ConsoleUtil;
import sc.tool.sqlgen.branchinfo.DiffUnit.DiffType;

/**
 *
 * <p>TODO:注释</p>
 * 到处比较后的结果
 * @author Zhang Yun
 * @version $Id: Store.java, v 0.1 2012-11-3 下午12:15:35 User Exp $
 */
public class Exporter implements ConsoleUtil {

    public void export() {
        Map<DiffType, List<String>> sqlMap = this.export2SQL(ResultHolder.getCompareResult());
        String timeStr = DateTime.now().toString("yyyyMMddHHmmss");
        if (!CollectionUtils.isEmpty(sqlMap.get(DiffType.NEW))) {
            System.out.println("-----------------开始打印Insert SQL-----------------");
            this.printSQL(sqlMap.get(DiffType.NEW));

            FileUtil.writeFile(sqlMap.get(DiffType.NEW), "D:/WeibopayMemo/出款服务FOS/icbc_insert.sql");
        }
        if (!CollectionUtils.isEmpty(sqlMap.get(DiffType.UPDATE))) {
            System.out.println("-----------------开始打印Update SQL-----------------");
            this.printSQL(sqlMap.get(DiffType.UPDATE));
            FileUtil.writeFile(sqlMap.get(DiffType.UPDATE), "D:/WeibopayMemo/出款服务FOS/icbc_update.sql");
        }
    }

    public void exportXlsx() {
        CompareResult compareResult = ResultHolder.getCompareResult();
        Console.info("准备导出，共{}条，差异数据", compareResult.getDiffCount());

        List<CreateSheet> sheets = new ArrayList<CreateSheet>();
        CreateSheet newSheet = null, updateSheet = null;
        for (DiffUnit unit : compareResult.getDiffUnitList()) {
            if (unit.getDiffType() == DiffType.NEW) {
                if (newSheet == null) {
                    List<String[]> title = new ArrayList<String[]>();
                    title.add(new String[] { "联行号", "分支行全称", "分支行别名", "行别代号", "银行编码", "省份Id", "城市Id", "是否默认" });
                    newSheet = new CreateSheet("新增分支行", title);
                }
                BranchInfo bi = unit.getBankData();
                newSheet.getDataRowList().add(
                        new String[] { bi.getBranchId(), bi.getBranchName(), bi.getBranchName(), bi.getUnifiedBankId(),
                                bi.getBankCode(), bi.getProvId(), bi.getCityId(), bi.getDefaultFlag() });
            } else if (unit.getDiffType() == DiffType.UPDATE) {
                if (updateSheet == null) {
                    List<String[]> title = new ArrayList<String[]>();
                    title.add(new String[] { "联行号", "差异内容", "原信息", "新信息", "新别名", "行别代号", "银行编码", "省份Id", "城市Id", "是否默认" });
                    updateSheet = new CreateSheet("更新分支行", title);
                }
                BranchInfo bi = unit.getBankData();
                for (Object[] diffField : unit.getDiffFileds()) {
                    updateSheet.getDataRowList().add(
                            new String[] { bi.getBranchId(), diffField[0] + "", diffField[1] + "", diffField[2] + "",
                                    "", bi.getUnifiedBankId(), bi.getBankCode(), bi.getProvId(), bi.getCityId(),
                                    bi.getDefaultFlag() });
                }
            }
        }
        if (newSheet != null) {
            sheets.add(newSheet);
        }
        if (updateSheet != null) {
            sheets.add(updateSheet);
        }
        XlsxUtil.writeFile("D:/WeibopayMemo/出款服务FOS/branh_info_new.xlsx", sheets);
        Console.info("实际导出，{}条新增数据，{}条更新数据", newSheet != null ? newSheet.dataRowList.size() : 0,
                updateSheet != null ? updateSheet.dataRowList.size() : 0);
    }

    public static final String INSERT_SQL_PATTERN = "insert into fos.tm_branch_info(id,branch_id,branch_name,default_flag,unified_bank_id,bank_code,prov_id,city_id,manual_flag,enable_flag,gmt_create,gmt_modified,memo) "
            + " values (fos.seq_branch_info.nextval, {0}, ''{1}'', ''{2}'', ''{3}'', ''{4}'', {5}, {6}, ''{7}'', ''{8}'', sysdate, sysdate, ''{9}'');";

    public static final String UPDATE_SQL_PATTERN = "update fos.tm_branch_info b"
            + " set b.bank_code = ''{0}'', b.branch_name = ''{1}'', b.city_id ={2}, b.prov_id = {3}"
            + " where b.branch_id = {4};";

    public Map<DiffType, List<String>> export2SQL(CompareResult compareResult) {
        if (compareResult == null || compareResult.getDiffCount() == 0) {
            //没有差异直接返回
            return null;
        }

        Map<DiffType, List<String>> sqlMap = new HashMap<DiffType, List<String>>();

        List<String> insertSQL = new ArrayList<String>();
        List<String> updateSQL = new ArrayList<String>();

        for (DiffUnit diffUnit : compareResult.getDiffUnitList()) {
            BranchInfo bankData = diffUnit.getBankData();
            String sql = null;
            switch (diffUnit.getDiffType()) {
            case NEW:
                sql = MessageFormat.format(INSERT_SQL_PATTERN, bankData.getBranchId(), bankData.getBranchName(), 'N',
                        bankData.getUnifiedBankId(), bankData.getBankCode(), bankData.getProvId(),
                        bankData.getCityId(), "N", "Y", "");

                insertSQL.add(sql);
                break;
            case UPDATE:
                sql = MessageFormat.format(UPDATE_SQL_PATTERN, bankData.getBankCode(), bankData.getBranchName(),
                        bankData.getCityId(), bankData.getCityId(), bankData.getBranchId());
                updateSQL.add(sql);
                break;
            }

            /*  if (insertSQL.size() % 100 == 0) {
                  insertSQL.add("commit;");
              }
              if (updateSQL.size() % 100 == 0) {
                  updateSQL.add("commit;");
              }*/
        }

        /*  if (!CollectionUtils.isEmpty(insertSQL)) {
              insertSQL.add("commit;");
          }

          if (!CollectionUtils.isEmpty(updateSQL)) {
              updateSQL.add("commit;");
          }*/
        sqlMap.put(DiffType.NEW, insertSQL);
        sqlMap.put(DiffType.UPDATE, updateSQL);

        return sqlMap;

    }

    private void printSQL(List<String> sqlList) {
        for (String sql : sqlList) {
            System.out.println(sql);
        }
    }

}
